package topic_service

import (
	"context"
	"encoding/json"
	"fmt"
	ark "github.com/sashabaranov/go-openai"
	"github.com/volcengine/volcengine-go-sdk/service/arkruntime/model"
	"github.com/volcengine/volcengine-go-sdk/volcengine"
	"io"
	"os"
	"video_demo/config"
	"video_demo/db"
	"video_demo/dto"
	"video_demo/entity"
	"video_demo/tools"
	"video_demo/vo"
)

func SaveSingleQuestion(topic *entity.Topic) error {
	if topic == nil {
		return fmt.Errorf("topic 参数不能为 nil")
	}

	base := db.GetDB()
	result := base.Create(topic)

	if result.Error != nil {
		return fmt.Errorf("数据库保存失败: %w", result.Error)
	}

	if result.RowsAffected == 0 {
		return fmt.Errorf("未创建任何记录")
	}
	return nil
}

func GetAllTopic(filter vo.TopicFilter) ([]entity.Topic, error) {
	base := db.GetDB()
	var topics []entity.Topic
	query := base.Model(&entity.Topic{})

	// 动态添加筛选条件
	if filter.Subject != "" {
		query = query.Where("subject = ?", filter.Subject)
	}
	if filter.Type != "" {
		query = query.Where("type = ?", filter.Type)
	}
	if filter.Difficulty != "" {
		query = query.Where("difficulty = ?", filter.Difficulty)
	}

	err := query.Find(&topics).Error
	if err != nil {
		return nil, fmt.Errorf("数据库查询失败: %w", err)
	}
	return topics, nil
}

/*func UploadQuestionFile(file io.Reader, fileExt string) ([]entity.Topic, error) {
	// 根据文件扩展名选择AI模型
	documentExtensions := map[string]bool{
		".pdf": true, ".txt": true, ".csv": true, ".docx": true, ".doc": true,
		".xlsx": true, ".xls": true, ".pptx": true, ".ppt": true, ".md": true,
		".mobi": true, ".epub": true,
	}

	model := config.SysConfig.AIModel.ThinkingModel
	content, err := io.ReadAll(file)
	if err != nil {
		return nil, fmt.Errorf("文件读取失败: %w", err)
	}

	if !documentExtensions[strings.ToLower(fileExt)] {

		// 将图片内容转换为 Base64 编码
		base64Img := base64.StdEncoding.EncodeToString(content)

		if _, err := base64.StdEncoding.DecodeString(base64Img); err != nil {
			fmt.Printf("Base64 编码错误: %v\n", err)
		}
		model = config.SysConfig.AIModel.VersionModel

		// 调用 OpenAI
		doubao := ark.DefaultConfig(os.Getenv("ARK_API_KEY"))
		doubao.BaseURL = "https://ark.cn-beijing.volces.com/api/v3"
		client := ark.NewClientWithConfig(doubao)

		req := ark.ChatCompletionRequest{
			Model: model,
			Messages: []ark.ChatCompletionMessage{
				{
					Role: ark.ChatMessageRoleUser,
					MultiContent: []ark.ChatMessagePart{
						{
							Type: ark.ChatMessagePartTypeText,
							Text: "请将以下题目内容解析为结构化JSON数据，包含题目、选项、答案、难度、解析、知识点字段。如果无法解析，请返回错误信息。" +
								"下面是题目数据样例: 其中的answer字段是选项中对应的答案，例如{\"1\":\"11\"}的答案是\"11\") " +
								"{\"subject\":\"math\",\"type\":\"single\",\"question\":\"1+12\",\"options\":{\"1\":\"11\",\"2\":\"12\",\"3\":\"13\",\"4\":\"14\"},\"answer\":\"14\",\"difficulty\":\"easy\",\"knowledge\":\"1+1=2\",\"analyze\":\"1+1=2\"}" +
								"不要直接把ABCD的选择直接给我，answer字段我只要正确的结果值，而不是A,B,C,D的选项",
						},
						{
							Type: ark.ChatMessagePartTypeImageURL,
							ImageURL: &ark.ChatMessageImageURL{
								URL: "data:image/jpeg;base64," + base64Img,
							},
						},
					},
				},
			},
		}

		resp, err := client.CreateChatCompletion(context.Background(), req)
		if err != nil {
			fmt.Printf("ChatCompletion error: %v\n", err)
			return nil, fmt.Errorf("AI解析失败: %w", err)
		}

		fmt.Println("结果 : ", resp.Choices[0].Message.Content)
	}

	// 调用AI解析接口
	doubao := ark.DefaultConfig(os.Getenv("ARK_API_KEY"))
	doubao.BaseURL = config.SysConfig.AIModel.URL
	client := ark.NewClientWithConfig(doubao)

	resp, err := client.CreateChatCompletion(context.Background(), ark.ChatCompletionRequest{
		Model: model,
		Messages: []ark.ChatCompletionMessage{
			{
				Role: ark.ChatMessageRoleSystem,
				Content: "请将以下题目内容解析为结构化JSON数据，包含题目、选项、答案、难度、解析、知识点字段。如果无法解析，请返回错误信息。" +
					"下面是题目数据样例:(其中的answer字段是选项中对应的答案，例如{\"1\":\"11\"}的答案是\"11\"),不要直接把ABCD的选择给我 " +
					"{\"subject\":\"math\",\"type\":\"single\",\"question\":\"1+12\",\"options\":{\"1\":\"11\",\"2\":\"12\",\"3\":\"13\",\"4\":\"14\"},\"answer\":\"14\",\"difficulty\":\"easy\",\"knowledge\":\"1+1=2\",\"analyze\":\"1+1=2\"}",
			},
			{
				Role:    ark.ChatMessageRoleUser,
				Content: string(content),
			},
		},
	})
	if err != nil {
		return nil, fmt.Errorf("AI解析失败: %w", err)
	}

	// 解析AI返回的JSON数据
	var topics []entity.Topic
	if err := json.Unmarshal([]byte(resp.Choices[0].Message.Content), &topics); err != nil {
		fmt.Println("解析数据 : ")
		return nil, fmt.Errorf("数据解析失败: %w", err)
	}

	return topics, nil
}*/

func UploadQuestionFile(file io.Reader, fileExt string) (interface{}, error) {
	// 初始化配置
	//ext := strings.ToLower(fileExt)
	cfg := ark.DefaultConfig(os.Getenv("ARK_API_KEY"))
	cfg.BaseURL = config.SysConfig.AIModel.URL
	client := ark.NewClientWithConfig(cfg)

	// 根据文件类型处理内容
	/*if isDocumentFile(ext) {
		return processDocumentFile(file, ext, client)
	}*/

	topics, _ := processImageFile(file, client)
	for index := range topics {
		topics[index].ID = index + 1
	}
	return topics, nil
}

func UploadBatchQuestion(questions string) ([]entity.Topic, error) {

	result, err := processBatchQuestion(questions)
	result = parseAIResponse(result)
	fmt.Println("result : ", result)

	if err != nil {
		return nil, fmt.Errorf("大模型请求失败: %w", err)
	}

	var topics []entity.Topic
	if err := json.Unmarshal([]byte(result), &topics); err != nil {
		return nil, fmt.Errorf("大模型返回格式JSON 解析失败: %w", err)
	}

	for index := range topics {
		topics[index].ID = index + 1
	}

	return topics, nil
}

func DeleteTopicByID(id string) error {
	base := db.GetDB()
	result := base.Where("id = ?", id).Delete(&entity.Topic{})
	if result.Error != nil {
		return fmt.Errorf("数据库删除失败: %w", result.Error)
	}
	if result.RowsAffected == 0 {
		return fmt.Errorf("未删除任何记录")
	}
	return nil
}

func ChatCompletion(c *entity.ChatClient, ctx context.Context, req *entity.ChatRequest) (*entity.ChatResponse, error) {
	// 自动添加系统提示
	messages := append([]*model.ChatCompletionMessage{
		{
			Role: model.ChatMessageRoleSystem,
			Content: &model.ChatCompletionMessageContent{
				StringValue: volcengine.String(c.SystemPrompt),
			},
		},
	}, req.Messages...)

	apiReq := model.BotChatCompletionRequest{
		Model:    c.BotID,
		Messages: messages,
	}

	resp, err := c.Client.CreateBotChatCompletion(ctx, apiReq)
	if err != nil {
		return nil, err
	}

	response := &entity.ChatResponse{
		Content: *resp.Choices[0].Message.Content.StringValue,
	}

	if resp.References != nil {
		response.References = make([]string, 0, len(resp.References))
		for _, ref := range resp.References {
			response.References = append(response.References, ref.Url)
		}
	}

	return response, nil
}

func GetAllTopicFilter(filter *vo.QueryTopic) (*dto.TopicFilterDTO, error) {
	base := db.GetDB()
	var topics []entity.Topic
	query := base.Model(&entity.Topic{})

	// 动态添加筛选条件
	if filter.Subject != "" {
		query = query.Where("subject = ?", filter.Subject)
	}
	if filter.Type != "" {
		query = query.Where("type = ?", filter.Type)
	}
	if filter.Difficulty != "" {
		query = query.Where("difficulty = ?", filter.Difficulty)
	}

	// 获取总数
	var totalRows int64
	err := query.Count(&totalRows).Error
	if err != nil {
		return nil, fmt.Errorf("查询总数据失败: %w", err)
	}
	//分页查询
	offset := (filter.PageNum - 1) * filter.PageSize
	err = query.Offset(offset).Limit(filter.PageSize).Find(&topics).Error
	if err != nil {
		return nil, fmt.Errorf("数据库查询失败: %w", err)
	}

	totalPages := int((totalRows + int64(filter.PageSize) - 1) / int64(filter.PageSize))

	pageResult := &dto.TopicFilterDTO{
		List:       topics,
		PageNum:    filter.PageNum,
		PageSize:   filter.PageSize,
		TotalRows:  totalRows,
		TotalPages: totalPages,
	}
	return pageResult, nil
}

func CreateTestPaper(paper *vo.TestPaper) (int, error) {
	testPaper := entity.TestPaper{
		Title:       paper.Title,
		QuestionIds: tools.ConvertInt64SliceToString(paper.QuestionIds),
		UserName:    paper.UserName,
		Status:      paper.Status,
	}
	result := db.GetDB().Create(&testPaper)
	if result.Error != nil {
		return 0, fmt.Errorf("数据库插入失败: %w", result.Error)
	}
	return testPaper.ID, nil
}

func CreateTestPaperInfo(ids *[]int64, paperID int) error {
	base := db.GetDB()

	var topics []entity.Topic
	err := base.Where("id in ?", *ids).Find(&topics).Error
	if err != nil {
		return fmt.Errorf("查询题目失败: %w", err)
	}

	var topicInfoList = make([]dto.TopicInfo, len(*ids))
	var answerInfoList = make([]dto.AnswerInfo, len(*ids))

	for index := range topics {
		topicInfoList[index].ID = topics[index].ID
		topicInfoList[index].Question = topics[index].Question
		topicInfoList[index].Options = topics[index].Options
		topicInfoList[index].Subject = topics[index].Subject
		topicInfoList[index].Type = topics[index].Type
		answerInfoList[index].ID = topics[index].ID
		answerInfoList[index].Answer = topics[index].Answer
	}

	var topicInfo string
	var answerInfo string
	topicInfo, err = dto.ConvertToJSON(topicInfoList)
	answerInfo, err = dto.ConvertToJSON(answerInfoList)

	testPaperInfo := entity.TestPaperInfo{
		TopicInfo:  topicInfo,
		AnswerInfo: answerInfo,
		PaperId:    paperID,
	}

	return db.GetDB().Create(&testPaperInfo).Error
}

func GetTestPapers(filter *vo.TestPaperFilter) (*dto.TestPaperFilterDTO, error) {
	var testPapers []entity.TestPaper
	var total int64

	base := db.GetDB().Model(&entity.TestPaper{})
	if filter.Search != "" {
		base = base.Where("title LIKE ? OR user_name LIKE ?", "%"+filter.Search+"%", "%"+filter.Search+"%")
	}
	// 状态过滤
	if filter.Status != "" {
		base = base.Where("status = ?", filter.Status)
	}

	if err := base.Count(&total).Error; err != nil {
		return nil, err
	}

	if err := base.Offset((filter.Page - 1) * filter.PageSize).Limit(filter.PageSize).Find(&testPapers).Error; err != nil {
		return nil, err
	}

	var testPaperFilterDTO = dto.TestPaperFilterDTO{
		List:       testPapers,
		PageNum:    filter.Page,
		PageSize:   filter.PageSize,
		TotalPages: int((total + int64(filter.PageSize) - 1) / int64(filter.PageSize)),
		TotalRows:  total,
	}

	return &testPaperFilterDTO, nil
}

func DeleteTestPaper(id string) error {
	dbInstance := db.GetDB().Model(&entity.TestPaper{})

	var paper entity.TestPaper
	err := dbInstance.Where("id = ?", id).First(&paper).Error
	if err != nil {
		return fmt.Errorf("未找到对应试卷")
	}

	// 判断该试卷是否进行审核
	if paper.Status == 0 || paper.Status == 1 {
		return fmt.Errorf("该试卷暂未进行审核，不可删除")
	}

	// 执行删除
	err = dbInstance.Where("id = ?", id).Delete(&entity.TestPaper{}).Error
	if err != nil {
		return fmt.Errorf("删除失败: %w", err)
	}
	return nil
}
